package com.lindroy.exception

import com.lindroy.config.RespResult
import org.springframework.http.HttpStatus
import org.springframework.http.converter.HttpMessageNotReadableException
import org.springframework.web.HttpMediaTypeNotSupportedException
import org.springframework.web.bind.MissingServletRequestParameterException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ResponseStatus
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.springframework.web.servlet.NoHandlerFoundException

/**
 * @author Lin
 * @date 2019/10/14
 * @function
 * @Description
 */
@RestControllerAdvice
class GlobalException {

    @ExceptionHandler(BaseException::class)
    fun handlerServiceException(e: BaseException): RespResult {
        return RespResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.message, false)
    }

    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NoHandlerFoundException::class)
    fun noHandlerFoundException(e: NoHandlerFoundException) = RespResult(HttpStatus.NOT_FOUND.value(), "Not Found ${e.message}")

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MissingServletRequestParameterException::class)
    fun handleMissingServletRequestParameterException(e: MissingServletRequestParameterException) =
        RespResult(HttpStatus.BAD_REQUEST.value(), "缺少请求参数 ${e.parameterName},类型:${e.parameterType}")

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException::class)
    fun handleHttpMessageNotReadableException(e: HttpMessageNotReadableException) =
        RespResult(HttpStatus.BAD_REQUEST.value(), "参数解析失败 ${e.message}")

    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler(HttpMediaTypeNotSupportedException::class)
    fun handleHttpMediaTypeNotSupportedException(e: HttpMediaTypeNotSupportedException)=
        RespResult(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value(), "Unsupported Media Type ${e.message}")


}